package org.example.order.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.order.VO.AdminVO;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.entity.Admin;
import org.example.order.entity.User;
import org.example.order.permission.Access;
import org.example.order.permission.AccessLevel;
import org.example.order.service.impl.AdminServiceImpl;
import org.example.order.service.impl.UserServiceImpl;
import org.example.order.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
@Slf4j
@Component
public class AccessInterceptor implements HandlerInterceptor {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private AdminServiceImpl adminService;
    @Value("${auth.sign: false}")
    boolean sign ;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        request.setAttribute("_startTime", System.currentTimeMillis());

        //**********************验权代码*************************
        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }
        Method method = handlerMethod.getMethod();
        Access access = method.getAnnotation(Access.class);

        if (access == null||!sign) {
            // 如果注解为null, 说明不需要拦截, 直接放过
            return true;
        }
        // 管理员
        if(access.level().getCode() == AccessLevel.ADMIN.getCode()) {
            String token=request.getHeader("Authorization");
            log.info("当前token为：[{}]",token);

            try {
                // 验证令牌
                DecodedJWT verify = JWTUtils.verify(token);
                Map<String, String> map=JWTUtils.getTokenData(token);
                log.info(map.get("level"));
                if (Integer.parseInt(map.get("level"))==AccessLevel.ADMIN.getCode())
                    return true;
                else {
                    APIResponse apiResponse=new APIResponse<>(ResponseCode.FAIL,"没有操作权限");
                    writeResponse(response, apiResponse);
                    return false;
                }
//                Admin admin=adminService.getById(map.get("id"));
//                if (admin != null) {
//                    return true;
//                } else {
//                    APIResponse apiResponse=new APIResponse<>(ResponseCode.FAIL,"不存在此id的管理员，请确认是否存在");
//                    writeResponse(response, apiResponse);
//                    return false;
//                }
            } catch (SignatureVerificationException e) {
                log.error(e.getMessage());
                APIResponse apiResponse= new APIResponse<>(ResponseCode.FAIL,"无效签名");
                writeResponse(response, apiResponse);
                return false;
            }catch (TokenExpiredException e){
                log.error(e.getMessage());
                APIResponse apiResponse=new APIResponse<>(ResponseCode.FAIL,"token过期");
                writeResponse(response, apiResponse);
                return false;
            }catch (AlgorithmMismatchException e){
                log.error(e.getMessage());
                APIResponse apiResponse= new APIResponse<>(ResponseCode.FAIL,"算法不一致");
                writeResponse(response, apiResponse);
                return false;

            }catch (Exception e){
                log.error(e.getMessage());
                APIResponse apiResponse=new APIResponse<>(ResponseCode.FAIL,"token无效！");
                writeResponse(response, apiResponse);
                return false;
            }

        }

        // 用户
//        if(access.level().getCode() == AccessLevel.LOGIN.getCode()) {
//            String token = request.getHeader("TOKEN");
//            logger.info("token==>" + token);
//            User user = userService.getUserByToken(token);
//            if(user != null && user.getRole().equals(String.valueOf(User.NormalUser))){
//                return true;
//            }else {
//                APIResponse apiResponse = new APIResponse(ResponeCode.FAIL, "未登录");
//                writeResponse(response, apiResponse);
//                return false;
//            }
//        }


        return true;
    }
    public void writeResponse(HttpServletResponse response, APIResponse apiResponse) throws IOException {
        response.setStatus(200);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Gson gson = new Gson();
        String jsonStr = gson.toJson(apiResponse);
        response.getWriter().println(jsonStr);
        response.getWriter().flush();
    }
}
